<template>
  <div class="goodList">
    <el-card>
      <div slot="header">
        <h2 v-if="!isEdit">泰康优选产品列表</h2>
        <h2 v-else>编辑产品列表</h2>
      </div>
      <div v-if="!isEdit" class="topSshow">
        <p>首页是否展示:</p>
        <el-radio-group @change="headShow" v-model="isShow">
          <el-radio :label="0">是</el-radio>
          <el-radio :label="1">否</el-radio>
        </el-radio-group>
      </div>
      <el-button v-if="!isEdit" @click="edit" type="primary"
        >编辑列表</el-button
      >
      <el-row>
        <el-col class="flexCenter" :span="10">
          <span>产品名称:</span>
          <el-input
            clearable
            class="ipts"
            placeholder="输入产品名称"
            size="small"
            v-model.trim="search.goodName"
          ></el-input>
        </el-col>
        <el-col class="flexCenter" :span="10">
          <span>产品编码:</span>
          <el-input
            clearable
            class="ipts"
            placeholder="请输入要查询的产品编码"
            size="small"
            v-model.trim="search.goodId"
          ></el-input>
        </el-col>
        <el-col class="flexCenter" :span="10">
          <span>产品来源:</span>
          <el-select
            class="bot"
            @change="selectOrigin"
            size="small"
            clearable
            v-model="search.channel"
            placeholder="请选择"
          >
            <el-option
              v-for="item in placeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-col>
        <el-col class="flexCenter" :span="10">
          <span>产品状态:</span>
          <el-select
            class="bot"
            @change="selectStatus"
            size="small"
            clearable
            v-model="search.goodStatus"
            placeholder="请选择"
          >
            <el-option
              v-for="item in goodsStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-col>
        <el-col class="btn" :span="3">
          <el-button size="small" type="primary" @click="doSearch"
            >查询</el-button
          >
        </el-col>
      </el-row>
      <el-row class="btns" v-if="isEdit">
        <el-col :span="4">
          <el-button size="small" type="primary" @click="addGoods"
            >+添加产品</el-button
          >
        </el-col>
        <el-col :span="4">
          <el-button
            size="small"
            :disabled="selectList.length == 0"
            type="danger"
            @click="delGoods"
            >删除产品</el-button
          >
        </el-col>
      </el-row>
    </el-card>
    <el-card class="tab">
      <el-table
        v-loading="loading"
        @selection-change="SelectionChange"
        :data="goods"
        :fit="true"
        border
        style="width: 100%"
      >
        <el-table-column
          v-if="isEdit"
          align="center"
          type="selection"
        ></el-table-column>
        <el-table-column
          fixed
          align="center"
          label="序号"
          type="index"
          width="60"
        ></el-table-column>
        <el-table-column
          fixed
          align="center"
          label="产品编号"
          prop="goodId"
          width="100"
        ></el-table-column>
        <el-table-column
          fixed
          align="center"
          prop="goodName"
          label="产品名称"
          width="150"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="picUrl"
          label="产品主图"
          style="text-align: center"
        >
          <template slot-scope="scope">
            <img :src="scope.row.picUrl" alt />
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="price"
          label="现/划线价"
          width="150"
        >
          <template slot-scope="scope">
            {{ scope.row.marketPrice/100 }} / {{ scope.row.originalPrice/100 }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="channel"
          label="产品来源"
        >
          <template slot-scope="scope">{{
            scope.row.channel == "A" ? "健投 " : "拜博"
          }}</template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="goodStatus"
          label="状态"
          width="100"
        >
          <template slot-scope="scope">{{
            scope.row.goodStatus == "0" ? "已上架 " : "已下架"
          }}</template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="salesVolume"
          label="总销量"
          width="100"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="gmtCreate"
          label="创建时间"
          width="130"
        >
        </el-table-column>
        <el-table-column v-if="isEdit" align="center" label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              @click="goDel(scope.row.id)"
              plain
              type="danger"
              size="small"
              >删除</el-button
            >
            <div class="col">
              <i
                @click="goDown(scope.row.id)"
                v-show="scope.row.id != goods[goods.length - 1].id"
                class="el-icon-bottom"
              ></i>
              <i
                @click="goUp(scope.row.id)"
                v-show="scope.row.id != goods[0].id"
                class="el-icon-top"
              ></i>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-row v-if="isEdit">
        <el-col class="rights" :span="24">
          <el-button @click="cancle">取消修改</el-button>
          <el-button type="primary" @click="done">完成</el-button>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import preferApi from "@/api/lejv/tkselect";
import _ from "lodash"; //引入lodash
export default {
  name: "Model",
  data() {
    return {
      isShow: "",
      isEdit: false,
      loading: false,
      selectList: [],
      goodsList: [],
      search: {
        goodName: "",
        goodId: "",
        goodStatus: "",
        channel: "",
      },
      placeList: [
        {
          value: "A",
          label: "健投",
        },
        {
          value: "B",
          label: "拜博",
        },
      ],
      goodsStatus: [
        {
          value: "0",
          label: "已上架",
        },
        {
          value: "1",
          label: "已下架",
        },
      ],
    };
  },
  //处理时间显示,后台已处理
  // filters: {
  //   timeFilter(times) {
  //     let timer = new Date(times);
  //     return timer.toLocaleDateString();
  //   },
  // },
  computed: {
    goods() {
      return this.sortByKey(this.goodsList, "preferredOrder"); //排序
    },
  },
  /* bug 存在删除后未点完成,继续添加的情况(方法:1:点击添加时将当前优选商品数组传递过去,
  将选择后的产品添加到该数组,再将该数组传递到优选页面渲染  ===>改方法仍存在bug  已删除的优选商品因为未点击完成,
  再次添加商品时不会出现在非优选商品列表)   当前采用此方法
  方法2: 后台添加删除接口   ====>此方法应该会对移动端显示有影响
  */
  created() {
    if (this.$route.params.type) {
      this.isEdit = true;
    } else {
      this.isEdit = false;
    }
    if (this.$route.params.selectGoods) {
      this.isEdit = true;
    }
    this.getList();
    this.getStatus()
  },
  mounted() {},
  methods: {
    //搜索
    doSearch() {
      this.getList();
    },
    //编辑列表
    edit() {
      this.$router.push({ name: "EditGoods", params: { type: 1 } });
    },
    //排序
    sortByKey(arr, key) {
      return arr.sort(function (a, b) {
        var x = a[key];
        var y = b[key];
        return x < y ? -1 : x > y ? 1 : 0;
      });
    },
    //添加产品
    addGoods() {
      if(this.goods.length >= 10){
        this.$message({
          type: "warning",
          message: "优选产品数量已达到限制，请删除后重新添加!",
        });
      }else{
        // this.$router.push("/content/choose?type=tkChoose");
        this.$router.push({name:"Choose",params:{type:"tkChoose",goods:this.goods}});
      }
      // this.$store.commit("app/select",this.goodsList)
    },
    //获取列表
    getList() {
      this.loading = true;
      let params = JSON.parse(JSON.stringify(this.search));
      params = _.pickBy(params, (item) => item); //使用lodash进行过滤参数为空的搜索条件
      preferApi
        .getPreferList(params)
        .then((res) => {
          // console.log(res);
          if (res.code == 0) {
            this.loading = false;
            this.goodsList = JSON.parse(JSON.stringify(res.data.goods));
            if (this.$route.params.selectGoods){ //如果是点击添加商品,则合并数组
              // this.goodsList = this.goodsList.concat(this.$route.params.selectGoods)
              this.goodsList = this.$route.params.selectGoods
              if(this.goodsList.length>10){
                this.goodsList = this.goodsList.slice(0,10)
              }
            }
            for (let i = 0; i < this.goodsList.length; i++) { //不管后台传递过来的参数,重新设置有序数字进行排序
              this.goodsList[i].preferredOrder = i;
            }
            // console.log(this.goodsList);
          }
        })
        .catch((res) => {
          this.loading = false;
        });
    },
    //多选删除产品
    delGoods() {
      this.$confirm("将从列表中删除该商品, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          for (let i = 0; i < this.selectList.length; i++) {
            this.goodsList = this.goodsList.filter(
              (item) => item.id != this.selectList[i].id
            );
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消删除!",
          });
        });
    },
    //获取首页展示状态
    getStatus(){
      preferApi.show()
      .then(res=>{
        // console.log(res);
        if(res.data == "false"){
          this.isShow = 1
        }else{
          this.isShow = 0
        }
      })
    },
    //编辑首页是否展示
    headShow(val) {
      let item = val == "0" ? "true" : "false"
      // console.log(val,item);
      preferApi.editShow({conValue:item})
      .then(res=>{
        if(res.code == 0){
          this.$message({
            type:"success",
            message:"操作成功!"
          })
        }else{
          this.$message({
            type:"error",
            message:"操作失败!"
          })
        }
      })
      .catch(res=>{
        this.$message({
          type:"error",
          message:"操作失败!"
        })
      })
    },
    //多选
    SelectionChange(val) {
      this.selectList = val;
      // console.log(this.selectList);
    },
    //选择来源
    selectOrigin(val) {
      // console.log(val);
      this.search.channel = val;
    },
    //选择状态
    selectStatus(val) {
      // console.log(val);
      this.search.showStatus = val;
    },
    //删除
    goDel(id) {
      // console.log(id);
      this.$confirm("将从列表中删除该商品, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.goodsList = this.goodsList.filter((item) => item.id != id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消删除!",
          });
        });
    },
    //上移 排序 获取上一行产品排序序号 与当前行产品进行交换
    goUp(id) {
      let currentIndex = this.goodsList.findIndex((item) => item.id == id);
      let currentOrder = this.goodsList[currentIndex].preferredOrder;
      this.goodsList[currentIndex].preferredOrder = this.goodsList[currentIndex - 1].preferredOrder;
      this.goodsList[currentIndex - 1].preferredOrder = currentOrder;
      // console.log(this.goodsList);
    },
    //下移 同上
    goDown(id) {
      let currentIndex = this.goodsList.findIndex((item) => item.id == id);
      let currentOrder = this.goodsList[currentIndex].preferredOrder;
      this.goodsList[currentIndex].preferredOrder = this.goodsList[currentIndex + 1].preferredOrder;
      this.goodsList[currentIndex + 1].preferredOrder = currentOrder;
    },
    //取消修改
    cancle() {
      this.$router.push("/content/tkChoose");
    },
    //修改完成
    done() {
      this.$confirm("将提交修改, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          let arr = [];
          for (let i = 0; i < this.goodsList.length; i++) {
            arr.push(this.goodsList[i].id);
          }
          let ids = arr.join(",");
          // console.log(this.goodsList,ids);
          preferApi
            .editPrefer({ idList: ids })
            .then((res) => {
              // console.log(res);
              if (res.msg == "success") {
                this.$message({
                  type: "success",
                  message: "修改成功!",
                });
                this.$router.push("/content/tkChoose");
              }else{
                this.$message({
                  type: "error",
                  message: res.msg,
                });
              }
              this.loading = false;
            })
            .catch((res) => {
              this.loading = false;
              this.$message({
                  type: "error",
                  message: "修改失败,请刷新后重试!",
                });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消修改!",
          });
          this.loading = false;
        });
    },
  },
};
</script>

<style scoped lang="scss">
.goodList {
  padding: 20px;
  .col {
    width: 80px;
  }
  ::v-deep.el-card__body{
    padding: 10px 20px;
  }
  ::v-deep.el-table .cell {
    display: flex;
    justify-content: center;
  }
  h2 {
    margin: 0;
  }
  .rights {
    text-align: right;
    margin-top: 40px;
  }
  img {
    width: 50px;
    height: 50px;
    object-fit: contain;
  }
  .btns {
    margin-top: 40px;
  }
  .el-icon-bottom,
  .el-icon-top {
    color: blue;
    width: 30px;
    line-height: 30px;
    cursor: pointer;
  }
  .el-icon-bottom:hover,
  .el-icon-top:hover {
    background-color: skyblue;
    border-radius: 5px;
  }
  .el-icon-bottom {
    margin: 0 10px;
  }
  .topSshow {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    p {
      margin-right: 30px;
    }
  }
  .flexCenter {
    display: flex;
    align-items: center;
    margin: 20px 10px 0 0;
    span {
      margin-right: 5px;
      font-size: 14px;
    }
    .ipts,
    .bot {
      width: 200px;
    }
  }
  .btn {
    text-align: right;
    margin-top: 20px;
  }
  .tab {
    margin-top: 20px;
  }
}
</style>
